package com.hb.znpt.viewmodel;

import android.app.Application;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.text.TextUtils;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.core.content.FileProvider;
import androidx.databinding.ObservableField;

import com.hb.znpt.BuildConfig;
import com.hb.znpt.activity.MainActivity;
import com.hb.znpt.bean.UpgradeBean;
import com.hb.znpt.model.LoginModel;
import com.hb.znpt.utils.CardJunit;
import com.hb.znpt.utils.Constants;
import com.hb.znpt.utils.LogUtils;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.rxjava.rxlife.RxLife;
import com.unitlib.base.base.BaseViewModel;
import com.unitlib.base.utils.SPUtils;
import com.unitlib.base.utils.ToastUtils;

import java.io.File;
import java.util.List;
import java.util.Objects;

import io.reactivex.android.schedulers.AndroidSchedulers;
import rxhttp.wrapper.param.RxHttp;

/**
 * @Description: 描述
 * @Author: houbing
 * @CreateDate: 2021/9/2 11:21
 */
public class LoginViewModel extends BaseViewModel<LoginModel> {

    public ObservableField<String> usercard = new ObservableField<>("");
    public ObservableField<String> username = new ObservableField<>("");

    private File mApkFile;

    public LoginViewModel(@NonNull Application application) {
        super(application);
        model = new LoginModel();
    }

    @Override
    public void onCreate() {
        usercard.set(SPUtils.getInstance().getString(Constants.SP_USERCARD));
        username.set(SPUtils.getInstance().getString(Constants.SP_USERNAME));
        XXPermissions.with(context)
                .permission(Permission.REQUEST_INSTALL_PACKAGES)
                .permission(Permission.READ_PHONE_STATE)
                .request(new OnPermissionCallback() {

                    @Override
                    public void onGranted(List<String> permissions, boolean all) {

                    }

                    @Override
                    public void onDenied(List<String> permissions, boolean never) {
                        if (never) {
                            ToastUtils.showShort("被永久拒绝授权，请手动授权限");
                            XXPermissions.startPermissionActivity(context, permissions);
                        }
                    }
                });

        if (SPUtils.getInstance().getBoolean(Constants.SP_LOGINSTATUS, false)) {
            startActivity(MainActivity.class);
            finish();
        }

        model.upgrade()
                .observeOn(AndroidSchedulers.mainThread())
                .as(RxLife.as(owner))
                .subscribe(bean -> {
                    int vc = Integer.parseInt(bean.getVersion());
                    if (BuildConfig.VERSION_CODE < vc) {
                        showUpdataDialog(bean);
                    }
                }, error -> {

                });
    }

    public void login(View view) {
        if (isEmpty()) {
            return;
        }
        model.login(usercard.get())
                .observeOn(AndroidSchedulers.mainThread())
                .doOnSubscribe(disposable -> {
                    getUC().getShowLoadingDialogEvent().call();
                })
                .doFinally(() -> {
                    getUC().getDismissLoadingDialogEvent().call();
                })
                .as(RxLife.as(owner))
                .subscribe(been -> {
                    SPUtils.getInstance().put(Constants.SP_LOGINSTATUS, true);
                    SPUtils.getInstance().put(Constants.SP_USERCARD, Objects.requireNonNull(usercard.get()));
                    SPUtils.getInstance().put(Constants.SP_USERNAME, Objects.requireNonNull(username.get()));
                    SPUtils.getInstance().put(Constants.SP_TOKEN, been);
                    startActivity(MainActivity.class);
                    finish();
                }, error -> {
                    ToastUtils.showShort(error.getMessage());
                });
    }

    private boolean isEmpty() {
        if (!CardJunit.is18ByteIdCardComplex(usercard.get())) {
            ToastUtils.showShort("请输入正确身份证号！");
            return true;
        }
        if (TextUtils.isEmpty(usercard.get())) {
            ToastUtils.showShort("请输入身份证！");
            return true;
        }
        return false;
    }

    public void showUpdataDialog(UpgradeBean bean) {
        AlertDialog.Builder normalDialog = new AlertDialog.Builder(context);
        normalDialog.setMessage("有新的安装包，是否更新?")
                .setTitle("更新提示")
                .setPositiveButton("现在更新", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        mApkFile = new File(context.getExternalFilesDir("down").getAbsoluteFile() +
                                "/" + System.currentTimeMillis() + ".apk");
                        dialog.dismiss();
                        ProgressDialog mpDialog = new ProgressDialog(context);
                        mpDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
                        mpDialog.setMessage("已下载");
                        mpDialog.setCancelable(false);
                        mpDialog.setCanceledOnTouchOutside(false);
                        RxHttp.get(bean.getUrl())
                                .asDownload(mApkFile.getPath(), AndroidSchedulers.mainThread(), progress -> {
                                    mpDialog.setMessage("已下载" + progress.getProgress() + "%");
                                })
                                .observeOn(AndroidSchedulers.mainThread())
                                .doOnSubscribe(disposable -> {
                                    mpDialog.show();
                                })
                                .doFinally(() -> {
                                    mpDialog.cancel();
                                })
                                .as(RxLife.as(owner))
                                .subscribe(s -> {
                                    LogUtils.e(TAG, "下载成功：" + s);
                                    installApk();
                                }, throwable -> {
                                    ToastUtils.showShort("下载失败！");
                                });
                    }
                })
                .setNegativeButton("稍后更新", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                }).show();

    }

    private void installApk() {
        XXPermissions.with(context)
                .permission(Permission.REQUEST_INSTALL_PACKAGES)
                .request(new OnPermissionCallback() {
                    @Override
                    public void onGranted(List<String> permissions, boolean all) {
                        if (all) {
                            Intent intent = new Intent();
                            intent.setAction(Intent.ACTION_VIEW);
                            Uri uri;

                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                                uri = FileProvider.getUriForFile(context, BuildConfig.APPLICATION_ID + ".fileprovider", mApkFile);
                                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
                            } else {
                                uri = Uri.fromFile(mApkFile);
                            }

                            intent.setDataAndType(uri, "application/vnd.android.package-archive");
                            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            context.startActivity(intent);
                        } else {
                            ToastUtils.showShort("应用安装权限被禁止，请手动授权限");
                            XXPermissions.startPermissionActivity(context, permissions);
                        }
                    }
                });
    }

}
